package com.openlogic.common.logic.func.aviator;

import java.util.Map;

import com.googlecode.aviator.runtime.function.AbstractVariadicFunction;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorRuntimeJavaType;
import com.openlogic.common.logic.func.ArithFunc;

/**
 * @ClassName: AverageFunc
 * @Description: 自定义均值函数 提供（相对）精确的计算平均数运算。当发生除不尽的情况时，精确到小数点以后10位，以后的数字四舍五入。
 * @author weiyongpeng
 * @date 2024年12月27日 上午10:16:43
 */
public class AverageFunc extends AbstractVariadicFunction {

	private static final long serialVersionUID = 1L;

	@Override
	public String getName() {
		return "cus_math.average";
	}

	@Override
	public AviatorObject variadicCall(Map<String, Object> env, AviatorObject... args) {
		double[] x = new double[args.length];
		for (int i = 0; i < args.length; i++) {
			Object value = args[i].getValue(env);
			if (value instanceof Long) {
				x[i] = (Double.parseDouble(String.valueOf((Long) value)));
			} else if (value instanceof Double) {
				x[i] = Double.parseDouble(String.valueOf(value));
			} else if (value instanceof Integer) {
				x[i] = Double.parseDouble(String.valueOf((Integer) value));
			} else {
				x[i] = Double.parseDouble(String.valueOf(value));
			}
		}
		double dSum = 0.0;
		int dCount = 0;
		for (double d : x) {
			dSum = ArithFunc.add(dSum, d);
			dCount++;
		}
		return AviatorRuntimeJavaType.valueOf(ArithFunc.div(dSum, dCount));
	}

}
